<template>
  <div class="user" style="padding: 0px;">
    <el-card>
      <el-form size="small" :inline="true" ref="searchForm" :model="searchForm" class="demo-form-inline">
        <!-- <el-form-item label="商品名称">
          <el-input size="small" v-model="searchForm.productName" placeholder="请输入商品名称" @keyup.enter.native="onSubmit"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="订单号">
          <el-input size="small" @keyup.enter.native="onSubmit" clearable v-model="searchForm.orderNo"
            placeholder="请输入订单号"></el-input>
        </el-form-item> -->
        <el-form-item label="提货人">
          <el-input size="small" v-model="searchForm.userName" placeholder="请输入提货人" @keyup.enter.native="onSubmit" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input size="small" v-model="searchForm.mobile" placeholder="请输入手机号" @keyup.enter.native="onSubmit" clearable></el-input>
        </el-form-item>
        <el-form-item label="下单时间">
          <div class="block">
            <span class="demonstration"></span>
            <el-date-picker size="small" v-model="searchForm.searchTime" type="daterange" value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="订单类型">
          <el-select clearable v-model="searchForm.orderType" placeholder="选择订单类型" size="default" style="width: 150px" @change="onSubmit">
            <el-option v-for="item in orderOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="选择基地" prop="produceId">
          <el-select clearable style="width: 200px;" v-model="searchForm.produceId">
            <el-option v-for="(adr, index) in produceAddressList" :key="index" :label="adr.produceName"
              :value="adr.produceAddrId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务员">
          <el-input size="small" v-model="searchForm.shopUserName" placeholder="请输入业务员名称" clearable></el-input>
        </el-form-item> -->
        <el-form-item>
          <el-button size="small" type="primary" icon="Search" @click="onSubmit">查询</el-button>
          <el-button icon="Refresh" @click="resetForm('searchForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  
    <el-card style="margin-top:5px;">
      <el-button size="small" icon="Download" @click="onExport" v-auth="'/order/operate/export'">导出订单</el-button>
      <el-button size="small" type="primary" icon="DocumentCopy" @click="onCreateOrder" v-auth="'/order/createorder'">生成订单</el-button>
      <el-tabs v-model="activeName" @tab-change="handleClick" type="border-card" style="margin-top:10px;">
        <el-tab-pane label="全部订单" name="all"></el-tab-pane>
        <template v-for="(item, index) in tabOptions" :key="index">
          <el-tab-pane :label="item.name" :name="item.name"></el-tab-pane>
        </template>
      </el-tabs>
      <el-table size="small" :data="tableData" border style="width: 100%;margin-top:-25px;" v-loading="loading" stripe>
        <el-table-column :label="col.label" :sortable="col.sortable" :align="col.algin" :fixed="col.fixed" :prop="col.prop" :width="col.width" v-for="(col, index) in columnMap[activeName]" :key="index">
          <template #default="scope" v-if="col.prop === 'orderNo'">
            <a @click="viewClick(scope.row, 'view')" href="javascript:;">{{ scope.row.orderNo }}</a>
          </template>
          <!-- yonyouCode -->
          <template #default="scope" v-if="col.prop === 'yonyouCode'">
            <el-tag type="warning" v-if="scope.row.yonyouCode" v-for="(val, index) in JSON.parse(scope.row.yonyouCode)">基地:{{ val.produceName }} 用友:{{ val.code }}</el-tag>
          </template>
          <template #default="scope" v-if="col.prop === 'isAudit'">
            <el-tag type="warning" v-if="scope.row.isAudit">是</el-tag>
            <el-tag type="warning" v-else>否</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="订单号" prop="orderNo" width="200"></el-table-column>
        <el-table-column label="提货人姓名" prop="extractName" width="150"></el-table-column>
        <el-table-column label="提货人手机" prop="extractPhone" width="160"></el-table-column>
        <el-table-column label="提货方式" prop="deliveryTypeText" width="160"></el-table-column>
        <el-table-column label="总价(优惠前)" prop="totalPrice" width="110"></el-table-column>
        <el-table-column label="总价(优惠后)" prop="orderPrice" width="110"></el-table-column>
        <el-table-column label="优惠券抵扣金额" prop="couponMoney" width="110"></el-table-column>
        <el-table-column label="积分抵扣金额" prop="pointsMoney" width="110"></el-table-column>
        <el-table-column label="定金" prop="depositPrice" width="100"></el-table-column>
        <el-table-column label="包装费" prop="packPrice" width="100"></el-table-column>
        <el-table-column label="尾款" prop="finalPrice" width="100"></el-table-column>
        <el-table-column label="(定金)支付方式" prop="payTypeText" width="110"></el-table-column> //*
        <el-table-column label="(尾款)支付方式" prop="finalPayTypeText" width="110"></el-table-column> //*
        <el-table-column label="订单类型" prop="orderSourceText" width="100"></el-table-column>
        <el-table-column label="用友单据编号" prop="yonyouCode" width="160"></el-table-column>
        <el-table-column label="付款链接" prop="urlLink" width="200"></el-table-column> //*
        <el-table-column label="创建时间" prop="createTime" width="150"></el-table-column>
        <el-table-column label="状态" prop="orderStatusText" width="100"></el-table-column>-->
        <!-- <el-table-column label="是否审核中" prop="isAudit" width="120">
          <template #default="scope">
            <el-tag type="warning" v-if="scope.row.isAudit">是</el-tag>
            <el-tag type="warning" v-else>否</el-tag>
          </template>
        </el-table-column>-->
        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template #default="scope">
            <el-button type="text" size="small" icon="View" v-if="scope.row.isAudit != 1 && scope.row.orderStatusText != '拼团中'" @click="viewClick(scope.row, 'view')">查看</el-button>
            <el-button type="text" size="small" icon="Printer" v-if="scope.row.isAudit != 1 && scope.row.orderStatusText != '拼团中'" @click="onPrint(scope.row)" class="fzlj">打印</el-button>
            <el-button v-if="scope.row.isAudit == 1 || scope.row.orderStatusText == '拼团中'" type="text" icon="View" size="small" @click="viewClick(scope.row, 'view')">查看</el-button>
            <el-dropdown trigger='hover' v-else>
              <span class="el-dropdown-link">
                更多
              <el-icon><d-arrow-right /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="exportCkClick(scope.row)" v-if="scope.row.orderButton.deliveryExportBtn" icon="Download">导出出库单</el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.orderButton.syncBtn" icon="Switch"> <span v-auth="'/order/order/cxtb'" @click="orderAsync(scope.row)">重新同步</span></el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.orderButton.canModify" icon="Edit"><span v-auth="'/order/order/xgsl'" @click="viewClick(scope.row, 'tz')">调整订单</span></el-dropdown-item>
                  <el-dropdown-item @click="orderClick(scope.row, '确认订单')" icon="CircleCheck" v-if="scope.row.orderButton.confirmBtn">确认订单</el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.orderButton.deliveryBtn" icon="Promotion"><span v-auth="'/order/order/delivery'" @click="goShipGoods(scope.row)">去发货</span></el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.orderButton.reverseApply" icon="Document"><span v-auth="'/order/order/delivery'" @click="applyCounterReview(scope.row)">申请反审</span></el-dropdown-item>
                  <el-dropdown-item @click="viewClick(scope.row, 'sh')" icon="Coin" v-if="scope.row.isAudit">财务审核</el-dropdown-item>
                  <el-dropdown-item @click="viewClick(scope.row, 'tk')" icon="Postcard" v-if="scope.row.orderButton.refundApply"><span v-auth="'/order/order/cwshsl'">退款申请</span></el-dropdown-item>
                  <el-dropdown-item @click="showFlowDialog(scope.row)" style="color:orange;" icon="Expand">流程图</el-dropdown-item>
                  <el-dropdown-item @click="copyLink(scope.row.urlLink)" style="color:green;" icon="Link">订单链接</el-dropdown-item>
                  <el-dropdown-item @click="cancelRow(scope.row)" icon="Close" style="color:red;" size="small" v-if="!(scope.row.orderStatusText == '已取消' || scope.row.orderStatusText == '已退款' || scope.row.orderStatusText == '退款中' || scope.row.orderStatusText == '已完成' || scope.row.orderStatusText == '审核中')">关闭</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="text" size="small" icon="Printer" @click="onPrint(scope.row)" v-if="scope.row.isAudit == 1 || scope.row.orderStatusText == '拼团中'" class="fzlj">打印</el-button>
            <el-button style="color:orange;" type="text" size="small" icon="Expand" @click="showFlowDialog(scope.row)" v-if="scope.row.isAudit == 1 || scope.row.orderStatusText == '拼团中'" class="fzlj">流程图</el-button>
            <el-button style="color:green;" v-if="scope.row.urlLink&&(scope.row.isAudit == 1 || scope.row.orderStatusText == '拼团中')" type="text" size="small" icon="Link" @click="copyLink(scope.row.urlLink)" class="fzlj">订单链接</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style="margin-top:10px;margin-bottom:10px;float:right;" @size-change="handleSizeChange" @current-change="handleCurrentChange" background :current-page="searchForm.pageIndex" :page-size="searchForm.pageSize" layout="total, prev, pager, next, jumper" :total="totalDataNumber"></el-pagination>
    </el-card>

    <!--内容-->
    <div class="product-content">
      <!-- 自提/发货处理 -->
      <el-dialog :title="fhTitle" v-model="fhShow" width="60%">
        <div class="common-form">基本信息</div>
        <el-form :model="fhModel" ref="form" label-width="100px">
          <div v-if="fhTitle === '快递发货'">
            <el-form-item label="快递类型" prop="kdlx">
              <el-select v-model="sendOrder.expressId">
                <el-option v-for="item in wlOptions" :key="item.expressId" :label="item.expressName" :value="item.expressId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="快递编号" prop="kdbh">
              <el-input v-model="sendOrder.expressNo"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="发货类型" prop="fhlx">
            <el-radio-group v-model="fhModel.fhlx">
              <el-radio size="large" :label="1" :value="1" name="全部发货">全部发货</el-radio>
              <el-radio size="large" :label="2" :value="2" name="部分发货">部分发货</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div v-if="fhModel.fhlx === 2">
          <div class="common-form">商品信息</div>
          <el-table :data="fhModel.fhProducts" style="width: 100%" max-height="350">
            <el-table-column prop="productName" label="操作" fixed="left" width="100">
              <template #default="scope">
                <el-button type="danger" @click="handlerRemove(scope.$index)" size="small">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="名称" width="180" />
            <el-table-column prop="productAttr" label="规格" width="300" />
            <el-table-column prop="sysl" label="剩余数量" width="130" fixed="right" />
            <el-table-column prop="num" label="发货数量" width="130" fixed="right">
              <template #default="scope">
                <el-input-number :min="0" v-model="scope.row.num" :max="scope.row.sysl" :controls="false" style="width: 90%"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="fhShowClick(false)">关闭</el-button>
            <el-button type="primary" :loading="btnloading" @click="fhShowClick(true)">确定</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 确认订单 -->
      <el-dialog title="确认订单" v-model="confirmShow" width="80%">
        <!-- 修改bug 去掉 -->
        <!-- <el-tag type="danger">
          {{
            confirmModel.payType === 40 ? "线下支付" : "线上支付"
          }}
        </el-tag> -->
        <br>
        <el-form v-if="confirmShow" :model="confirmModel" ref="confirmModel" label-width="140px">
          <el-form-item label="订单号" prop="orderNumber">
            <el-input v-model="confirmModel.orderNumber" disabled />
          </el-form-item>
          <el-form-item label="提货时间" prop="pickupTime">
            <el-date-picker v-model="pickupTime" format="YYYY/MM/DD" value-format="YYYY-MM-DD" style="width: 100%;" type="date" placeholder="选择日期" @change="onPickupTimeChange()"></el-date-picker>
          </el-form-item>
          <el-divider>
            提货时间
          </el-divider>
          <el-table v-loading="showProductsLoading" size="small" :data="confirmModel.showProducts" border
            style="width: 100%">
            <el-table-column prop="productName" label="标题"></el-table-column>
            <el-table-column prop="productAttr" label="规格属性"></el-table-column>
            <el-table-column prop="totalNum" label="购买数量" width="80"></el-table-column>
            <el-table-column prop="depositPrice" label="已付定金" width="100"></el-table-column>
            <el-table-column prop="expectDeliveryTime" label="预计发货日期"></el-table-column>
            <el-table-column prop="productAddress" label="生产部门" width="100"></el-table-column>
            <el-table-column prop="pickupTime" label="提货时间">
              <template #default="scope">
                <el-date-picker :disabled-date="($event) => disabledBefore($event, scope.row.expectDeliveryTime)" v-model="scope.row.pickupTime" format="YYYY/MM/DD" value-format="YYYY-MM-DD" style="width: 100%;" type="date" placeholder="选择日期" @change="onDateChange($event, scope.row)"></el-date-picker>
              </template>
            </el-table-column>
          </el-table>
          <!-- <el-form-item
            label="提货时间"
            prop="pickupTime"
            :rules="[{ required: true, message: '请选择提货时间' }]"
          >
            
          </el-form-item>-->
          <!-- 确认订单 线下支付 -->
          <!-- <div v-show="confirmModel.payType === 40">
            <el-form-item label="付款截图" prop="fileId" :rules="[
              { required: confirmModel.payType === 40, message: '请上传付款截图' },
            ]">
              <el-upload class="avatar-uploader" v-model:fileList="fileList" :auto-upload="false" :limit="1"
                :show-file-list="true">
                <img v-if="imageInfo.imageUrl" style="width: 100px; height: 100px" :src="imageInfo.imageUrl"
                  class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </div> -->
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="orderCancle">关闭</el-button>
            <el-button type="primary" :loading="btnloading" @click="orderSave">确定</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 确认尾款 -->
      <el-dialog title="确认尾款" v-model="backShow" width="30%">
        <el-form :model="backForm" ref="backForm" label-width="160px">
          <el-form-item label="订单号" prop="orderNumber">
            <el-input v-model="backForm.orderNumber" disabled />
          </el-form-item>
          <el-form-item label="订单号ID" prop="orderId">
            <el-input v-model="backForm.orderId" disabled />
          </el-form-item>
          <el-form-item label="付款截图" prop="fileId" :rules="[{ required: true, message: '请上传付款截图' }]">
            <el-upload class="avatar-uploader" v-model:fileList="fileList" :auto-upload="false" :limit="1" :show-file-list="true">
              <img v-if="imageInfo.imageUrl" style="width: 100px; height: 100px" :src="imageInfo.imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="wkCancle">关闭</el-button>
            <el-button type="primary" :loading="wkLoad" @click="wkOrderSave">确定</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 选择生成订单的商品 -->
      <el-dialog title="生成订单" v-model="orderCreate" width="100%" top="5vh" :close-on-click-modal="false">
        <div class="common-form mt16">基础信息</div>
        <el-form :inline="true" :rules="postFormRules" style="width: 90%;margin: 0 auto;" :model="postForm" ref="postForm" class="demo-form-inline">
          <!-- <el-form-item label="选择基地" prop="produceAddress">
            <el-select style="width: 200px;" v-model="postForm.produceAddress" @change="selProduceAddress">
              <el-option v-for="(adr, index) in produceAddressList" :key="index" :label="adr.produceName"
                :value="adr.produceAddrId"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="选择客户" prop="userName">
            <!-- <el-input style="width: 200px;" size="small" readonly v-model="postForm.userName">
              <template #append>
                <el-button type="primary" @click="onSelectUser">选择</el-button>
              </template>
            </el-input> -->
            <el-select filterable placeholder='请选择客户' style="width: 200px;" @change="selUser" v-model="postForm.userName">
              <el-option v-for="(adr, index) in khList" :key="index" :label="`姓名:${adr.realName}；电话:${adr.mobile}`" :value="adr.userId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="订单类型" prop="orderType">
            <el-radio-group v-model="postForm.orderType">
              <el-radio :label="20" border>上门自提</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="address" label="收货地址" v-if="postForm.orderType === 10">
            <el-select v-model="postForm.address">
              <el-option v-for="(adr, index) in userAddressList" :key="index" :label="`${adr.provinceName}/${adr.cityName}/${adr.regionName}/${adr.detail}`" :value="adr.addressId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="ztAdress" label="自提地址" v-if="postForm.orderType === 20">
            <el-select style="width: 200px;" v-model="postForm.ztAdress">
              <el-option v-for="(adr, index) in ztAddress" :key="index" :label="adr.storeName" :value="adr.storeId"></el-option>
            </el-select>
          </el-form-item>


          <!-- <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item> -->
        </el-form>
        <div class="common-form mt16">商品信息</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <div style="display: flex;justify-content: space-between;align-items: center;">
              <p style="margin-top: 20px">商品列表</p>
              <div>
                <div>
                  <el-input size="small" v-model="orderProductForm.productName" placeholder="请输入关键字查询" style=" margin: 5px 0px" @keyup.enter.native="productSearch">
                    <template #append>
                      <el-button type="primary" @click="productSearch">查询</el-button>
                    </template>
                  </el-input>
                </div>
              </div>
            </div>
            <el-table style="width: 100%" border :data="orderProducts" v-loading="orderProductLoading" max-height="350" stripe>
              <el-table-column prop="productName" label="名称" width="180" />
              <el-table-column prop="categoryParentName" label="品种" width="100" align="center" />
              <el-table-column prop="categoryName" label="分类" width="100" align="center" />
              <el-table-column prop="spec" label="规格" width="280">
                <template #default="scope">{{ scope.row.color }},{{ scope.row.sku }}</template>
              </el-table-column>
              <el-table-column prop="stockNum" label="库存" width="80" align="center" />
              <el-table-column prop="productPrice" label="单价" width="130" align="center">
                <template #default="scope">￥{{ scope.row.productPrice || '0.00' }}</template>
              </el-table-column>
              <el-table-column prop="tenThousandPrice" label="满一万单价" width="130" align="center">
                <template #default="scope">￥{{ scope.row.tenThousandPrice || '0.00' }}</template>
              </el-table-column>
              <el-table-column prop="lakhPrice" label="满十万单价" width="130" align="center">
                <template #default="scope">￥{{ scope.row.lakhPrice || '0.00' }}</template>
              </el-table-column>
              <el-table-column prop="depositRatio" label="定金比例" width="130" align="center" />
              <el-table-column prop="produceAddressTxt" label="种植基地" width="130" align="center" />
              <el-table-column prop="num" label="操作" width="100" fixed="right">
                <template #default="scope">
                  <el-button @click="orderPSClick(scope.row)" icon="CircleCheck">选择</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pageselect">
              <el-pagination background :default-page-size="orderProductForm.pageSize" @current-change="prodcutCurrent" layout="prev, pager, next,total" :total="spTotal" />
            </div>
          </el-col>
          <el-col :span="12">
            <div style="display: flex;justify-content: space-between;align-items: center;">
              <p style="margin-top: 20px">已选商品</p>
              <div>
                <!-- 优惠券信息 -->
                <!-- couponTypeText	优惠券类型(10满减券 20折扣券 30核销券 40商品券 50购买券 60充值券) -->
                选择优惠券 <el-select @change="selCouponType" style="width: 200px;" v-model="userCouponId" placeholder="请选择">
                  <el-option v-for="item in couponList" :key="item.userCouponId" :label="item.name" :value="item.userCouponId">
                    <div style="float: left">
                      {{ item.name }}
                    </div>
                    <span style="margin-left: 10px; float: right; color: #8492a6; font-size: 13px">
                      <el-tag size="mini">
                        {{ item.couponTypeText }}
                      </el-tag>
                    </span>
                  </el-option>
                </el-select>
              </div>
            </div>
            <el-table style="width: 100%" border :data="orderSelctProduct" v-loading="slCaleLoading" max-height="350" stripe>
              <el-table-column prop="productName" label="名称" width="180" />
              <el-table-column prop="categoryParentName" label="品种" width="100" align="center" />
              <!-- <el-table-column prop="categoryName" label="分类" width="100" />
              <el-table-column prop="spec" label="规格" width="300">
                <template #default="scope">{{ scope.row.color }},{{ scope.row.sku }}</template>
              </el-table-column> -->
              <!-- <el-table-column prop="stockNum" label="库存" width="100" /> -->
              <!-- <el-table-column prop="produceAddressTxt" label="种植基地" width="130" /> -->
              <el-table-column prop="orderProductType" label="商品类型" width="130" align="center">
                <template #default="scope">
                  <el-select v-model="scope.row.orderProductType" placeholder="请选择商品类型" @change="selCoupon">
                    <el-option :label="item1.name" :value="item1.id" v-for="(item1, index1) in orderProductTypeList" :key="index1"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="sl" label="数量" width="130" align="center">
                <template #default="scope">
                  <el-input-number v-if="scope.row.categoryParentName == '种苗'" @change="selCoupon" :min="scope.row.minBuyCount" v-model="scope.row.sl" style="width: 95%" :controls="false" />
                  <el-input-number v-else @change="selCoupon" :min="scope.row.minBuyCount" v-model="scope.row.sl" :max="scope.row.stockNum" style="width: 95%" :controls="false" />
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" width="200">
                <template #default="scope">
                  <el-input type="textarea" placeholder="请输入内容" maxlength="100" show-word-limit v-model="scope.row.remark" />
                </template>
              </el-table-column>
              <el-table-column prop="productPrice" label="单价" width="130" align="center">
                <template #default="scope">￥{{ scope.row.productPrice || '0.00' }}</template>
              </el-table-column>
              <el-table-column prop="tenThousandPrice" label="满一万单价" width="130" align="center">
                <template #default="scope">￥{{ scope.row.tenThousandPrice || '0.00' }}</template>
              </el-table-column>
              <el-table-column prop="lakhPrice" label="满十万单价" width="130" align="center">
                <template #default="scope">￥{{ scope.row.lakhPrice || '0.00' }}</template>
              </el-table-column>
              <!-- <el-table-column prop="depositRatio" label="定金比例" width="100">
                <template #default="scope">
                  <el-tooltip content="请填写小数，如 50% 请填写 0.5">
                    <el-input-number :min="0" :max="1" v-model="scope.row.depositRatio" style="width: 95%"
                      :controls="false" />
                  </el-tooltip>
                </template>
              </el-table-column> -->

              <el-table-column prop="couponPrice" label="优惠金额" width="150" align="center">
                <template #default="scope">￥{{ scope.row.couponPrice || '0.00' }}</template>
              </el-table-column>
              <el-table-column prop="depositRatio" label="定金比例" v-auth="'/order/order/xgsl'" width="150" align="center">
              </el-table-column>
              <el-table-column prop="depositPrice" label="定金价格" v-auth="'/order/order/xgsl'" width="150" align="center">
              </el-table-column>
              <el-table-column prop="finalPrice" label="尾款" width="150" align="center">
                <template #default="scope">￥{{ scope.row.finalPrice || '0.00' }}</template>
              </el-table-column>
              <el-table-column prop="packagePrice" label="包装费" width="150" align="center">
                <template #default="scope">￥{{ scope.row.packagePrice || '0.00' }}</template>
              </el-table-column>
              <el-table-column prop="totalPayPrice" label="总金额" width="150" align="center">
                <template #default="scope">￥{{ scope.row.totalPayPrice || '0.00' }}</template>
              </el-table-column>
              <el-table-column prop="num" label="操作" width="100" fixed="right">
                <template #default="scope">
                  <el-button type="danger" @click="orderPDelete(scope.$index)" icon="CircleClose">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <!-- 赠品 -->
        <div class="common-form mt16" v-if="giftProduct && giftProduct.length">赠品信息</div>
        <el-table size="small" v-if="giftProduct && giftProduct.length" :data="giftProduct" border style="width: 100%">
          <el-table-column prop="imagePath" label="商品图片">
            <template #default="scope">
              <img :src="scope.row.imagePath || scope.row.skuVo.imagePath" style="width: 60px ; height:60px" />
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="赠品名称"></el-table-column>
          <el-table-column label="规格">
            <template #default="scope">
              {{ scope.row.productAttr || scope.row.skuVo.productAttr }}
            </template>
          </el-table-column>
          <el-table-column prop="buyNum" label="数量"></el-table-column>
          <el-table-column prop="produceName" label="生产基地">
            <template #default="scope">
              {{ scope.row.produceName }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
        </el-table>
        <!-- 修改后订单信息 -->
        <div class="common-form mt16" v-if="JSON.stringify(CalcData) != '{}'">新订单信息</div>
        <el-row justify=center v-if="JSON.stringify(CalcData) != '{}'" :gutter="30" class="calc-data-css">
          <el-col span="3">
            <span>优惠金额:</span>￥{{ CalcData.couponPrice || '0.00' }}
          </el-col>
          <el-col span="3">
            <span>定金:</span>￥{{ CalcData.depositTotalPrice || '0.00' }}
          </el-col>
          <el-col span="3">
            <span>尾款:</span>￥{{ CalcData.finalTotalPrice || '0.00' }}
          </el-col>
          <el-col span="3">
            <span>包装费:</span>￥{{ CalcData.packagePrice || '0.00' }}
          </el-col>
          <el-col span="3">
            <span>总金额:</span>￥{{ CalcData.totalPrice || '0.00' }}
          </el-col>
          <el-col span="3">
            <span>优惠后总金额:</span>￥{{ CalcData.orderPayPrice || '0.00' }}
          </el-col>
        </el-row>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="onCreaeOrderCancle">关闭</el-button>
            <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled" icon-color="#626AEF" title="确认创建订单?" @confirm="onCreaeOrderSave">
              <template #reference>
                <el-button type="primary" :loading="orderloading">创建订单</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-dialog>
      <!-- 选择用户 -->
      <el-dialog title="选择用户" v-model="customerShow" top="10vh" width="55%">
        <p style="margin: 10px 0px; padding: 0px">
          <el-input size="small" v-model="userForm.keyword" placeholder="请输入关键字查询" style="width: 40%">
            <template #append>
              <el-button type="primary" @click="onSelectUserSearch">查询</el-button>
            </template>
          </el-input>
        </p>
        <el-table style="width: 100%" v-loading="utableLoading" :data="khList" max-height="300">
          <el-table-column prop="userId" label="ID" width="100" />
          <el-table-column prop="realName" label="客户名称" width="180" />
          <el-table-column prop="nickName" label="客户昵称" />
          <el-table-column prop="mobile" label="手机号" width="130" />
          <el-table-column prop="controls" label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button :type="scope.row.userId === selectUserId ? 'primary' : ''"
                @click="userSopeSelect(scope.row)">{{ scope.row.userId === selectUserId ? "已选" : "选择" }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pageselect">
          <el-pagination background @current-change="khCurrentChange" layout="prev, pager, next" :total="khTotal" />
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="onSelectUserCacnle">关闭</el-button>
            <el-button type="primary" @click="onSelectUserSave">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 去发货 -->
    <el-dialog v-model="addTitleShow" :title="addGoShipTitle" width="90%" @close="addTitleShow = false" :close-on-click-modal="false">
      <add v-if="addTitleShow" @closeDialog="closeDialog" :rowData="rowData"></add>
    </el-dialog>
    <el-dialog title="选择赠品商品" v-model="giftListShow" width="90%" top="5vh">
      <el-table size="small" :data="orderSelctProduct" border style="width: 100%;height: 300px;">
        <el-table-column prop="imagePath" label="封面">
          <template #default="scope">
            <img :src="scope.row.imagePath" style="width: 60px ; height:60px" />
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="标题" width="300"></el-table-column>
        <el-table-column prop="productAttr" label="规格属性" width="300"></el-table-column>
        <el-table-column prop="productAddress" label="生产部门" width="150"></el-table-column>
        <el-table-column prop="ctl" label="操作" fixed="right" width="100">
          <template #default="scope">
            <el-button type="success" @click="rowGift(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 打印 -->
    <el-dialog title="打印订单" v-model="printShow" width="70%">
      <print v-if="printShow" :Seltemplate='Seltemplate' :id="printRow.orderId"></print>
    </el-dialog>
    <!-- 申请反审 -->
    <el-dialog title="申请反审" v-model="FSShow" width="30%" :before-close="handleClose">
      <div style="margin-bottom: 40px;" v-if="FSShow">
        <p>
          <span style="color: red;">*</span>申请反审原因:
          <el-input style="width: 60%;" type="textarea" v-model="desc" />
        </p>
      </div>
      <div style="text-align: center;">
        <el-button type="primary" @click="FSSave()" v-loading="applyCounterLoading">提交</el-button>
      </div>
    </el-dialog>
    <!-- 打印模版 -->
    <el-dialog title="打印模版" v-model="templateShow" width="80%" :before-close="handleClose" :close-on-click-modal="false">
      <el-card style="margin-top:-10px;">
        <printTemplateIndex SelType="select" @SelChange='SelChange'></printTemplateIndex>
      </el-card>
    </el-dialog>
    <el-dialog title="操作流程" v-model="flowDialog" width="60%" :before-close="handleClose">
      <nextFlowImg :order="rowDta" :history-steps="historySteps" :current-step="currentStep" :next-steps="nextSteps" @branch-action="handleBranchAction"></nextFlowImg>
    </el-dialog>

  </div>
</template>
<script>
import OrderApi from "@/api/order.js";
import PorductApi from "@/api/product.js";
import UserApi from "@/api/user";
import StoreApi from "@/api/store";
import { useUserStore } from "@/store";
import { ElMessage, ElMessageBox } from "element-plus";
import { defaultPageSize } from "@/utils/table.js";
import add from "@/views/order/shipping/add.vue"
import printTemplateIndex from "@/views/setting/print-template/index.vue"
import nextFlowImg from "./next-flow-img.vue"
import print from "./print.vue"
const { token } = useUserStore();
export default {
  components: { add, print, printTemplateIndex, nextFlowImg },
  data() {
    return {
      giftListShow: false,
      templateShow: false,
      CalcData: {},
      applyCounterLoading: false,
      Seltemplate: {},
      desc: '',
      FSShow: false,
      FSRow: {},
      printShow: false,
      printRow: {},
      showProductsLoading: false,
      couponList: [],
      produceAddressList: [],//基地集合
      userCouponId: '',
      giftProduct: [],
      token,
      addGoShipTitle: "去发货",
      addTitleShow: false,
      rowData: {},
      /*切换菜单*/
      activeName: "all",
      /*是否加载完成*/
      loading: false,
      fhShow: false,
      confirmShow: false,
      backShow: false,
      slCaleLoading: false,
      fhTitle: "",
      /*列表数据*/
      tableData: [],
      // 10-销售 20-赠品 30-赔付
      orderProductTypeList: [
        {
          name: '销售',
          id: 10
        },
        {
          name: '赠品',
          id: 20
        },
        {
          name: '赔付',
          id: 30
        }
      ],
      refOptions: [20, 30],
      /*表单验证规则*/
      rules: {
        orderNo: [
          {
            required: true,
            message: "请输入订单号",
            trigger: "blur",
          },
        ],
      },
      /*一页多少条*/
      pageSize: defaultPageSize,
      /*一共多少条数据*/
      totalDataNumber: 0,
      /*当前是第几页*/
      curPage: 1,
      /*横向表单数据模型*/
      searchForm: {
        orderType: null,
        startDate: "",
        endDate: "",
        orderNo: "",
        keyword: "",
        userName: '',
        searchTime: "",
        dataType: "all",
        pageIndex: 1,
        pageSize: 10,
      },
      postFormRules: {
        produceAddress: [
          { required: true, message: '请选择基地', trigger: 'change' }
        ],
        userName: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        orderType: [
          { required: true, message: '请选择订单类型', trigger: 'change' }
        ],
        ztAdress: [
          { required: true, message: '请选择自提地址', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请选择收货地址', trigger: 'change' }
        ],
      },
      /*配送方式*/
      exStyle: [],
      /*门店列表*/
      shopList: [],
      /*时间*/
      create_time: "",
      /*统计*/
      order_count: {
        payment: 0,
        delivery: 0,
        received: 0,
      },
      logisticsData: {},
      dialogBatchDelivery: false,
      /*是否打开编辑弹窗*/
      open_edit: false,
      /*当前编辑的对象*/
      order_no: "",
      isLogistics: false,
      fileterValue: "all",
      fhModel: {
        kdlx: "",
        kdbh: "",
        fhlx: 2,
        fhProducts: [],
      },
      confirmModel: {
        orderNumber: "",
        orderId: "",
        pickupTime: "",
        payType: 0,
        fileId: "",
        paySource: "", //线下支付渠道
        payTime: "", //线下支付时间
        tradeNo: "", //线下支付流水号
        showProducts: [],
        products: [],
      },
      backForm: {
        orderNumber: "",
        orderId: "",
        paySource: "",
        payTime: "",
        tradeNo: "",
        fileId: "",
      },
      wkLoad: false,
      tabOptions: [
        // notSettle-待结算 audit-审核中
        // 之前 待支付1 待确认2 待发货5 待自提4 待评价7 已评价8 退款10 已取消11 待结算 
        { name: "待支付", value: 1, filter: "payment" },
        { name: "待确认", value: 2, filter: "notConfirm" },
        // { name: "待结算", value: 12, filter: "notSettle" },
        { name: "审核中", value: 13, filter: "audit" },
        { name: "待发货", value: 5, filter: "delivery" },
        { name: "待自提", value: 4, filter: "notPickup" },
        { name: "待评价", value: 7, filter: "notComment" },
        { name: "已评价", value: 8, filter: "commented" },
        { name: "退款", value: 10, filter: "refund" },
        { name: "已取消", value: 11, filter: "cancel" },

      ],
      orderOptions: [
        { label: "拼团", value: 1 },
        { label: "秒杀", value: 2 },
        { label: "预售", value: 3 },
        { label: "普通", value: 4 },
        { label: "进口苗", value: 5 },
        { label: "特惠", value: 6 },
      ],
      btnControls: [],
      sendOrder: {
        orderId: 0,
        expressNo: "",
        expressId: "",
        allDelivery: false,
        productList: [],
      },
      wlOptions: [],
      btnloading: false,
      payType: 0,
      orderCreate: false,
      customerShow: false,
      customerRow: null,
      orderProducts: [],
      userForm: {
        pageIndex: 1,
        pageSize: 999999,
        keyword: "",
      },
      khList: [],
      khTotal: 0,
      selectUserId: "",
      postForm: {
        userId: "",
        userName: "",
        orderType: 20, //  20 自提
        address: "",
        ztAdress: "",
        produceAddress: ''
      },
      orderProductForm: {
        pageIndex: 1,
        pageSize: 20,
        productName: "",
      },
      orderProductLoading: false,
      spTotal: 0,
      orderSelctProduct: [],
      userAddressList: [],
      ztAddress: [],
      orderloading: false,
      utableLoading: false,
      flowDialog: false,
      cwTkForm: {
        show: false,
        id: "",
      },
      pickupTime: '',
      fileList: [],
      imageInfo: {
        imageId: "",
        imageUrl: "",
      },
      controlMap: {
        'all': 380,
        '待支付': 250,
        '待确认': 380,
        '待付尾款': 330,
        '待发货': 300,
        '待自提': 300,
        '待收货': 300,
        '待评价': 180,
        '已评价': 250,
        '退款': 200,
        '已取消': 180
      },
      columnMap: {
        'all': [
          { label: '订单号', prop: "orderNo", width: '200',algin: 'center',fixed: 'left',sortable: 'sortable'},
          { label: '提货人姓名', prop: "extractName", width: '160',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人手机', prop: "extractPhone", width: '120',algin: 'center',sortable: 'sortable' },
          { label: '提货方式', prop: "deliveryTypeText", width: '100',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠前)', prop: "totalPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠后)', prop: "orderPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '优惠券抵扣金额', prop: "couponMoney", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '积分抵扣金额', prop: "pointsMoney", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '定金', prop: "depositPrice", width: '100',algin: 'center',sortable: 'sortable' },
          { label: '包装费', prop: "packPrice", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '尾款', prop: "finalPrice", width: '100',algin: 'center',sortable: 'sortable' },
          // { label: '(定金)支付方式', prop: "payTypeText", width: '150' },
          // { label: '(尾款)支付方式', prop: "finalPayTypeText", width: '140' },
          { label: '订单类型', prop: "orderSourceText", width: '120',algin: 'center',sortable: 'sortable' },
          { label: '用友单据编号', prop: "yonyouCode", width: '260',sortable: 'sortable' },
          // { label: '付款链接', prop: "urlLink", width: '150' },
          { label: '创建时间', prop: "createTime", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '状态', prop: "orderStatusText", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '订单分类', prop: "orderCategory", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '创建人', prop: "creater", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '是否审核中', prop: "isAudit", width: '150',algin: 'center',sortable: 'sortable' },
          // { label: '是否有生成订单审批', prop: "createOrderAuditBtn", width: '200' },
          // { label: '付款单是否有审批', prop: "billAudit", width: '200' },

        ],
        '待支付': [
          { prop: "orderNo", label: '订单号', width: '200',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { prop: "extractName", label: '提货人姓名', width: '160',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { prop: "extractPhone", label: '提货人手机', width: '160',algin: 'center',sortable: 'sortable' },
          { prop: "totalPrice", label: '总价(优惠前)', width: '130',algin: 'center',sortable: 'sortable' },
          { prop: "orderPrice", label: '总价(优惠后)', width: '130',algin: 'center',sortable: 'sortable' },
          { prop: "orderSourceText", label: '订单类型', width: '100',algin: 'center',sortable: 'sortable' },
          // { prop: "urlLink", label: '付款链接', width: '260' },
          { prop: "createTime", label: '创建时间', width: '150',algin: 'center',sortable: 'sortable' },
          { label: '订单分类', prop: "orderCategory", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '创建人', prop: "creater", width: '150',algin: 'center',sortable: 'sortable' },
        ],
        '待结算': [
          { label: '订单号', prop: "orderNo", width: '200',algin: 'center',fixed: 'left' },
          { label: '提货人姓名', prop: "extractName", width: '160',algin: 'center',fixed: 'left' },
          { label: '提货人手机', prop: "extractPhone", width: '160',algin: 'center' },
          { label: '提货方式', prop: "deliveryTypeText", width: '160',algin: 'center' },
          { label: '总价(优惠前)', prop: "totalPrice", width: '110',algin: 'center' },
          { label: '总价(优惠后)', prop: "orderPrice", width: '110',algin: 'center' },
          { label: '优惠券抵扣金额', prop: "couponMoney", width: '160',algin: 'center' },
          { label: '积分抵扣金额', prop: "pointsMoney", width: '160',algin: 'center' },
          { label: '定金', prop: "depositPrice", width: '100',algin: 'center' },
          { label: '包装费', prop: "packPrice", width: '150',algin: 'center' },
          { label: '尾款', prop: "finalPrice", width: '100',algin: 'center' },
          // { label: '(定金)支付方式', prop: "payTypeText", width: '150' },
          // { label: '(尾款)支付方式', prop: "finalPayTypeText", width: '140' },
          { label: '订单类型', prop: "orderSourceText", width: '150',algin: 'center' },
          { label: '创建时间', prop: "createTime", width: '150',algin: 'center' },
          { label: '需退款的金额', prop: "needRefundAmount", width: '170',algin: 'center' },
          { label: '状态', prop: "orderStatusText", width: '150',algin: 'center' },
          { label: '是否审核中', prop: "isAudit", width: '150',algin: 'center' },
          { label: '订单分类', prop: "orderCategory", width: '150',algin: 'center' },
          { label: '创建人', prop: "creater", width: '150',algin: 'center' },
        ],
        '审核中': [
          { label: '订单号', prop: "orderNo", width: '200',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人姓名', prop: "extractName", width: '160',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人手机', prop: "extractPhone", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '提货方式', prop: "deliveryTypeText", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠前)', prop: "totalPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠后)', prop: "orderPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '优惠券抵扣金额', prop: "couponMoney", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '积分抵扣金额', prop: "pointsMoney", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '定金', prop: "depositPrice", width: '100',algin: 'center',sortable: 'sortable' },
          { label: '包装费', prop: "packPrice", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '尾款', prop: "finalPrice", width: '100',algin: 'center',sortable: 'sortable' },
          // { label: '(定金)支付方式', prop: "payTypeText", width: '150' },
          // { label: '(尾款)支付方式', prop: "finalPayTypeText", width: '140' },
          { label: '订单类型', prop: "orderSourceText", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '创建时间', prop: "createTime", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '状态', prop: "orderStatusText", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '是否审核中', prop: "isAudit", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '订单分类', prop: "orderCategory", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '创建人', prop: "creater", width: '150',algin: 'center',sortable: 'sortable' },
        ],
        '待确认': [
          { label: '订单号', prop: "orderNo", width: '200',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人姓名', prop: "extractName", width: '160',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人手机', prop: "extractPhone", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '提货方式', prop: "deliveryTypeText", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠前)', prop: "totalPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠后)', prop: "orderPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '优惠券抵扣金额', prop: "couponMoney", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '积分抵扣金额', prop: "pointsMoney", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '定金', prop: "depositPrice", width: '100',algin: 'center',sortable: 'sortable' },
          // { label: '(定金)支付方式', prop: "payTypeText", width: '150' },
          { label: '订单类型', prop: "orderSourceText", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '用友单据编号', prop: "yonyouCode", width: '260',algin: 'center',sortable: 'sortable' },
          { label: '创建时间', prop: "createTime", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '订单分类', prop: "orderCategory", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '创建人', prop: "creater", width: '150',algin: 'center',sortable: 'sortable' },
        ],
        '待付尾款': [
          { label: '订单号', prop: "orderNo", width: '200' },
          { label: '提货人姓名', prop: "extractName", width: '160' },
          { label: '提货人手机', prop: "extractPhone", width: '160' },
          { label: '提货方式', prop: "deliveryTypeText", width: '160' },
          { label: '总价(优惠前)', prop: "totalPrice", width: '110' },
          { label: '总价(优惠后)', prop: "orderPrice", width: '110' },
          { label: '优惠券抵扣金额', prop: "couponMoney", width: '160' },
          { label: '积分抵扣金额', prop: "pointsMoney", width: '160' },
          { label: '定金', prop: "depositPrice", width: '100' },
          { label: '包装费', prop: "packPrice", width: '150' },
          { label: '尾款', prop: "finalPrice", width: '100' },
          // { label: '(定金)支付方式', prop: "payTypeText", width: '150' },
          // { label: '(尾款)支付方式', prop: "finalPayTypeText", width: '140' },
          { label: '订单类型', prop: "orderSourceText", width: '150' },
          { label: '用友单据编号', prop: "yonyouCode", width: '260' },
          { label: '创建时间', prop: "createTime", width: '150' },
          { label: '订单分类', prop: "orderCategory", width: '150' },
          { label: '创建人', prop: "creater", width: '150' },
        ],
        '待发货': [
          { label: '订单号', prop: "orderNo", width: '200',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人姓名', prop: "extractName", width: '160',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人手机', prop: "extractPhone", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '提货方式', prop: "deliveryTypeText", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠前)', prop: "totalPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠后)', prop: "orderPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '订单类型', prop: "orderSourceText", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '用友单据编号', prop: "yonyouCode", width: '260',algin: 'center',sortable: 'sortable' },
          // { label: '付款链接', prop: "urlLink", width: '150' },
          { label: '创建时间', prop: "createTime", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '订单分类', prop: "orderCategory", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '创建人', prop: "creater", width: '150',algin: 'center',sortable: 'sortable' },
        ],
        '待自提': [
          { label: '订单号', prop: "orderNo", width: '200',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人姓名', prop: "extractName", width: '160',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人手机', prop: "extractPhone", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '提货方式', prop: "deliveryTypeText", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠前)', prop: "totalPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠后)', prop: "orderPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '订单类型', prop: "orderSourceText", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '用友单据编号', prop: "yonyouCode", width: '260',algin: 'center',sortable: 'sortable' },
          // { label: '付款链接', prop: "urlLink", width: '200' },
          { label: '创建时间', prop: "createTime", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '订单分类', prop: "orderCategory", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '创建人', prop: "creater", width: '150',algin: 'center',sortable: 'sortable' },
        ],
        '待收货': [
          { label: '订单号', prop: "orderNo", width: '200' },
          { label: '提货人姓名', prop: "extractName", width: '160' },
          { label: '提货人手机', prop: "extractPhone", width: '160' },
          { label: '提货方式', prop: "deliveryTypeText", width: '160' },
          { label: '总价(优惠前)', prop: "totalPrice", width: '110' },
          { label: '总价(优惠后)', prop: "orderPrice", width: '110' },
          { label: '订单类型', prop: "orderSourceText", width: '150' },
          { label: '用友单据编号', prop: "yonyouCode", width: '260' },
          // { label: '付款链接', prop: "urlLink", width: '200' },
          { label: '创建时间', prop: "createTime", width: '150' },
          { label: '订单分类', prop: "orderCategory", width: '150' },
          { label: '创建人', prop: "creater", width: '150' },
        ],
        '待评价': [
          { label: '订单号', prop: "orderNo", width: '200',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人姓名', prop: "extractName", width: '160',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人手机', prop: "extractPhone", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '提货方式', prop: "deliveryTypeText", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠前)', prop: "totalPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠后)', prop: "orderPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '订单类型', prop: "orderSourceText", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '用友单据编号', prop: "yonyouCode", width: '260',algin: 'center',sortable: 'sortable' },
          // { label: '付款链接', prop: "urlLink", width: '200' },
          { label: '创建时间', prop: "createTime", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '订单分类', prop: "orderCategory", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '创建人', prop: "creater", width: '150',algin: 'center',sortable: 'sortable' },
        ],
        '已评价': [
          { label: '订单号', prop: "orderNo", width: '200',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人姓名', prop: "extractName", width: '160',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人手机', prop: "extractPhone", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '提货方式', prop: "deliveryTypeText", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠前)', prop: "totalPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠后)', prop: "orderPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '订单类型', prop: "orderSourceText", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '用友单据编号', prop: "yonyouCode", width: '260',algin: 'center',sortable: 'sortable' },
          // { label: '付款链接', prop: "urlLink", width: '200' },
          { label: '创建时间', prop: "createTime", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '订单分类', prop: "orderCategory", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '创建人', prop: "creater", width: '150',algin: 'center',sortable: 'sortable' },
        ],
        '退款': [
          { label: '订单号', prop: "orderNo", width: '200',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人姓名', prop: "extractName", width: '160',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人手机', prop: "extractPhone", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '提货方式', prop: "deliveryTypeText", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠前)', prop: "totalPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠后)', prop: "orderPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '订单类型', prop: "orderSourceText", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '用友单据编号', prop: "yonyouCode", width: '260',algin: 'center',sortable: 'sortable' },
          // { label: '付款链接', prop: "urlLink", width: '200' },
          { label: '创建时间', prop: "createTime", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '订单分类', prop: "orderCategory", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '创建人', prop: "creater", width: '150',algin: 'center',sortable: 'sortable' },
        ],
        '已取消': [
          { label: '订单号', prop: "orderNo", width: '200',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人姓名', prop: "extractName", width: '160',algin: 'center',fixed: 'left',sortable: 'sortable' },
          { label: '提货人手机', prop: "extractPhone", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '提货方式', prop: "deliveryTypeText", width: '160',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠前)', prop: "totalPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '总价(优惠后)', prop: "orderPrice", width: '130',algin: 'center',sortable: 'sortable' },
          { label: '订单类型', prop: "orderSourceText", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '用友单据编号', prop: "yonyouCode", width: '260',algin: 'center',sortable: 'sortable' },
          // { label: '付款链接', prop: "urlLink", width: '200' },
          { label: '创建时间', prop: "createTime", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '订单分类', prop: "orderCategory", width: '150',algin: 'center',sortable: 'sortable' },
          { label: '创建人', prop: "creater", width: '150',algin: 'center',sortable: 'sortable' },
        ]
      },
      // 下一步操作流程图
      orderId: null,
      order: {
        id: '1001',
        orderNo: 'ORD20240630001',
        createTime: '2024-06-30 10:30:45',
        status: 'processing',
        statusText: '处理中',
        // 其他订单信息...
      },
      historySteps: [],
      currentStep: null,
      nextSteps: [],
      rowDta: {},
      //  <el-table-column label="订单号" prop="orderNo" width="200"></el-table-column>
      //         <el-table-column label="提货人姓名" prop="extractName" width="150"></el-table-column>
      //         <el-table-column label="提货人手机" prop="extractPhone" width="160"></el-table-column>
      //         <el-table-column label="提货方式" prop="deliveryTypeText" width="160"></el-table-column>
      //         <el-table-column label="总价(优惠前)" prop="totalPrice" width="110"></el-table-column>
      //         <el-table-column label="总价(优惠后)" prop="orderPrice" width="110"></el-table-column>
      //         <el-table-column label="优惠券抵扣金额" prop="couponMoney" width="110"></el-table-column>
      //         <el-table-column label="积分抵扣金额" prop="pointsMoney" width="110"></el-table-column>
      //         <el-table-column label="定金" prop="depositPrice" width="100"></el-table-column>
      //         <el-table-column label="包装费" prop="packPrice" width="100"></el-table-column>
      //         <el-table-column label="尾款" prop="finalPrice" width="100"></el-table-column>
      //         <el-table-column label="(定金)支付方式" prop="payTypeText" width="110"></el-table-column>
      //         <el-table-column label="(尾款)支付方式" prop="finalPayTypeText" width="110"></el-table-column>
      //         <el-table-column label="订单类型" prop="orderSourceText" width="100"></el-table-column>
      //         <el-table-column label="用友单据编号" prop="yonyouCode" width="160"></el-table-column>
      //         <el-table-column label="付款链接" prop="urlLink" width="200"></el-table-column>
      //         <el-table-column label="创建时间" prop="createTime" width="150"></el-table-column>
      //         <el-table-column label="状态" prop="orderStatusText" width="100"></el-table-column>

    };
  },
  created() {
    /*获取列表*/
    // 先选择基地在获取商品
    this.getData();
    this.getjdList();

  },
  watch: {
    fileList: {
      handler(n, v) {
        if (n && n.length > 0) {
          const { raw } = n[0];
          this.onUploadImage(raw);
        }
      },
      deep: true,
    },
  },

  methods: {
    resetForm(formName) {
      this.searchForm = {};
      this.getData();
    },
    /*关闭*/
    cancelRow: function (row) {
      let self = this;

      PorductApi.orderClose({
        orderId: row.orderId
      }).then(data => {
        ElMessage({
          message: '关闭成功',
          type: 'success'
        });
        self.getData();
      });

    },
    SelChange(row) {
      this.printShow = true;
      this.Seltemplate = row
      this.templateShow = false;
    },
    // 打印
    onPrint(row) {
      // 先选择模版
      this.templateShow = true;
      this.printRow = row;

    },
    // 下一步流程图
    showFlowDialog(row) {
      this.flowDialog = true;
      // 模拟API请求，实际应该从后端获取
      // 这里仅作为示例数据
      OrderApi.orderOperate({ orderId: row.orderId }).then(res => {
        const { code, data } = res;
        console.log(code, data)
        // 历史步骤
        this.rowDta = row;
        this.historySteps = data.history
        this.currentStep = data.current
      })


      // 下一步可能的分支
      this.nextSteps = [
        // {
        //   id: 'ship',
        //   title: '发货',
        //   description: '商家将订单商品打包并发货',
        //   type: 'normal',
        //   typeText: '标准流程',
        //   conditions: '库存充足，地址有效',
        //   canExecute: true,
        //   actionText: '发货'
        // }
      ];
    },
    // 处理分支操作
    handleBranchAction(branch) {
      this.$confirm(`确定要执行 "${branch.title}" 操作吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟API请求
        this.$message({
          type: 'success',
          message: `成功执行操作: ${branch.title}`
        });

        // 刷新订单数据
        // 实际应用中应该调用API更新订单状态后重新获取数据
        this.simulateNextStep(branch.id);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },

    // 模拟执行下一步后的状态变化
    simulateNextStep(branchId) {
      if (branchId === 'ship') {
        // 添加到历史步骤
        this.historySteps.push(this.currentStep);

        // 更新当前步骤
        this.currentStep = {
          title: '已发货',
          description: '商家已发货，等待配送',
          time: new Date().toLocaleString(),
          operator: '李四'
        };

        // 更新下一步
        this.nextSteps = [
          {
            id: 'deliver',
            title: '配送中',
            description: '物流公司正在配送',
            type: 'normal',
            typeText: '标准流程',
            canExecute: true,
            actionText: '确认配送'
          }
        ];

        // 更新订单状态
        this.order.status = 'shipped';
        this.order.statusText = '已发货';
      } else if (branchId === 'wait_stock') {
        // 添加到历史步骤
        this.historySteps.push(this.currentStep);

        // 更新当前步骤
        this.currentStep = {
          title: '备货中',
          description: '商家正在备货',
          time: new Date().toLocaleString(),
          operator: '李四'
        };

        // 更新下一步
        this.nextSteps = [
          {
            id: 'ship',
            title: '发货',
            description: '商家将订单商品打包并发货',
            type: 'normal',
            typeText: '标准流程',
            canExecute: true,
            actionText: '发货'
          },
          {
            id: 'cancel',
            title: '取消订单',
            description: '因特殊情况需要取消订单',
            type: 'special',
            typeText: '异常处理',
            canExecute: true,
            actionText: '取消订单'
          }
        ];

        // 更新订单状态
        this.order.status = 'stocking';
        this.order.statusText = '备货中';
      } else if (branchId === 'cancel') {
        // 添加到历史步骤
        this.historySteps.push(this.currentStep);

        // 更新当前步骤
        this.currentStep = {
          title: '已取消',
          description: '订单已取消',
          time: new Date().toLocaleString(),
          operator: '李四'
        };

        // 清空下一步
        this.nextSteps = [];

        // 更新订单状态
        this.order.status = 'cancelled';
        this.order.statusText = '已取消';
      }
    },
    // 下一步流程图

    onPickupTimeChange() {

      // 外面选择了日期可以同步到列表里面
      this.confirmModel.showProducts.map(val => {
        val['pickupTime'] = this.pickupTime
        const currnetTime = new Date(val.pickupTime);
        const afterTime = new Date(val.expectDeliveryTime);
        if (currnetTime.getTime() < afterTime.getTime()) {
          ElMessage.error("发货时间不能小于预计发货时间");
          this.pickupTime = ''
          val.pickupTime = ''
        }
      })
    },
    FSSave() {
      this.applyCounterLoading = true
      OrderApi.modifyApply({ orderId: this.FSRow.orderId, desc: this.desc }, true).then(res => {
        const { code, data } = res;
        console.log(data, 'data+++++')
        this.applyCounterLoading = false
        if (code == 1) {
          ElMessage.success("提交成功");
          this.getData();
          this.FSShow = false

        }
      }).catch(e => {
        this.applyCounterLoading = false

      })
    },
    // 申请反审
    applyCounterReview(row) {
      this.FSRow = row;
      this.FSShow = true;
      this.desc = ''

    },
    disabledBefore(time, oldTime) {
      console.log(time, oldTime, '3456')
      // 设定不能选择的指定时间，比如2023年1月1日
      const limitTime = new Date(oldTime).getTime();
      return time.getTime() <= limitTime;
    },
    getjdList() {
      OrderApi.productProduceList().then(res => {
        console.log(res, 'res---')
        const { code, data } = res;
        if (code == 1) {
          this.produceAddressList = data;
        }
      })
    },
    selProduceAddress(e) {
      this.loadProducts();
      this.orderSelctProduct = [];

    },
    rowGift(row) {
      this.giftListShow = false;
      this.giftProduct = [row]
      this.selCoupon()
    },
    // 选择商品券弹窗选择商品
    selCouponType(val) {
      console.log(val, 'val-----')
      let row = {}
      this.couponList.map(item => {
        if (item.userCouponId == val) {
          row = item
        }
      })
      if (row.couponType == 40) {
        // 商品券需要选择商品
        this.giftListShow = true;
      } else {
        this.selCoupon()
      }
    },
    // 选择优惠券 编辑数量
    selCoupon() {
      this.$forceUpdate();
      this.orderSelctProduct = JSON.parse(JSON.stringify(this.orderSelctProduct))
      this.orderSelctProduct.map(val => {
        val.buyNum = val.sl;
      })
      this.$nextTick(() => {
        this.orderModifyCalc();
      })
    },
    // 计算接口
    orderModifyCalc() {
      if (this.orderSelctProduct.length == 0) {
        return false;
      }
      let Obj = {
        orderId: '',
        couponId: this.userCouponId,
        userId: this.postForm.userId,
        productParams: this.orderSelctProduct,
        giftProduct: this.giftProduct[0]
      }
      this.slCaleLoading = true;
      OrderApi.orderModifyCalc(Obj, true).then(res => {
        const { code, data, msg } = res;
        this.slCaleLoading = false;
        if (code == 1) {
          console.log(data, 'data')
          // 数据清空
          this.couponList = [];
          this.userCouponId = '';
          this.CalcData = data;
          this.couponList = data.couponList;
          data.userCouponVo && (this.userCouponId = data.userCouponVo.userCouponId)
          // 赠品
          if (data.giftProduct) {
            this.giftProduct = [data.giftProduct];
          }
          // 商品信息
          if (data.productList) {
            this.orderSelctProduct.map(val => {
              data.productList.map(item => {
                if (val.productId == item.productId) {
                  val.couponPrice = item.couponPrice
                  val.depositPrice = item.depositPrice
                  val.packagePrice = item.packagePrice
                  val.totalPayPrice = item.totalPayPrice
                  val.finalPrice = item.finalPrice
                }
              })
            })
          }
          // 强制刷新
          this.couponList = JSON.parse(JSON.stringify(this.couponList))
        } else {
          return ElMessage.error(msg);
        }

      }).catch(e => {
        this.slCaleLoading = false;

      })
    },
    // 去发货
    goShipGoods(row) {
      this.addGoShipTitle = '去发货'
      this.addTitleShow = true;
      this.rowData = row;
    },
    closeDialog() {
      this.addTitleShow = false;
    },
    onClear() { },
    onDateChange($event, row) {
      const currnetTime = new Date($event);
      const afterTime = new Date(row.expectDeliveryTime);
      if (currnetTime.getTime() < afterTime.getTime()) {
        ElMessage.error("发货时间不能小于预计发货时间");
        row.pickupTime = ''
        return
      }
    },
    onUploadImage(raw) {
      const $this = this;
      var form = new FormData();
      form.append("iFile", raw);
      OrderApi.imageUpload(form, true)
        .then((result) => {
          const { code, data, msg } = result;
          if (code === 1) {
            ElMessage.success(msg);
            $this.imageInfo.imageId = data.fileId;
            $this.imageInfo.imageUrl = data.filePath;
            $this.confirmModel.fileId = data.fileId;
            $this.backForm.fileId = data.fileId;
            $this.fileList = [];
          } else {
            ElMessage.error(msg);
            $this.fileList = [];
          }
        })
        .catch((error) => {
          ElMessage.error("上传失败");
        });
    },
    async copyLink(linkText) {
      const $this = this;
      await $this.$copyText(linkText);
      ElMessage.success("复制成功");
    },
    onCreateOrder() {
      this.loadKhList();
      this.loadZtAdress();
      this.orderCreate = true;
      this.getjdList();
      // 进页面就查商品 不需要基地
      this.loadProducts();

    },
    userSopeSelect(row) {
      this.customerRow = row;
      this.selectUserId = row.userId;
    },
    onCreaeOrderSave() {
      // const $this = this;
      // //确认订单
      // const json = {
      //   products: $this.orderSelctProduct,
      //   ...$this.postForm,
      // };
      // if (!json.userId || !json.userName) {
      //   ElMessage.error("请选择用户");
      //   return;
      // }
      // if (json.orderType === 10 && !json.address) {
      //   ElMessage.error("请选择客户收货地址");
      //   return;
      // }
      // if (json.orderType === 20 && !json.ztAdress) {
      //   ElMessage.error("请选择自提地址");
      //   return;
      // }
      // if (json.products.length <= 0) {
      //   ElMessage.error("请选择需要生成订单的商品");
      //   return;
      // }
      if (!this.orderSelctProduct.length || this.orderSelctProduct.some(val => !val.orderProductType)) {
        ElMessage.error("请维护商品类型");
        return;
      }
      this.$refs['postForm'].validate((valid) => {
        if (valid) {
          this.postCreateOrder();

        } else {
          return false;
        }
      });
    },
    postCreateOrder() {
      const $this = this;
      // 最新参数
      let obj = {
        orderId: '',
        storeId: this.postForm.ztAdress,
        couponId: this.userCouponId,
        userId: this.postForm.userId,
        productParams: this.orderSelctProduct,
        giftProduct: this.giftProduct[0]
      }
      const postbody = {
        userId: $this.postForm.userId,
        deliveryType: $this.postForm.orderType,
        phone: "",
        linkman: "",
        storeId: $this.postForm.ztAdress,
        skus: [],
        addressVo: {},
      };
      if (postbody.deliveryType === 20) {
        //如果是自提，地址默认是用户地址
        const user = $this.khList.find((f) => f.userId === $this.postForm.userId);
        if (user) {
          postbody.linkman = user.realName;
          postbody.phone = user.mobile;
        }
      }
      //如果是快递发货，使用用户选择的地址
      if (postbody.deliveryType === 10 && $this.userAddressList) {
        const shModel = $this.userAddressList.find(
          (f) => f.addressId === $this.postForm.address
        );
        if (shModel) {
          postbody.addressVo = shModel;
          postbody.linkman = shModel.name;
          postbody.phone = shModel.phone;
        }
      }

      const pds = $this.orderSelctProduct;
      //处理商品
      postbody.skus = pds.map((f) => {
        return {
          productSkuId: f.productSkuId,
          depositRatio: f.depositRatio,
          num: f.sl,
        };

      });
      // fix 去掉之前的
      // postbody
      $this.orderloading = true;
      OrderApi.createOrderNew(obj, true)
        .then((result) => {
          $this.orderloading = false;
          const { code, msg, data } = result;
          if (code === 1) {
            ElMessage.success(msg);
            setTimeout(() => {
              $this.orderCreate = false;
              $this.orderClearnForm();
            }, 600);
            $this.onSubmit();
            // 拿到data跳转到详情
            $this.$router.push({
              path: "/order/order/Detail",
              query: {
                id: data,
                tk: 'view',
              },
            });
          } else {
            ElMessage.error(msg);
            $this.orderloading = false;
          }
        })
        .catch((error) => {
          $this.orderloading = false;
        });
    },
    orderClearnForm() {
      this.postForm.userId = "";
      this.postForm.userName = "";
      this.postForm.orderType = 10;
      this.postForm.address = "";
      this.postForm.ztAdress = "";
      this.orderSelctProduct = [];
      this.orderCreate = false;
    },
    onCreaeOrderCancle() {
      this.orderClearnForm();
    },
    onSelectUser() {
      this.selectUserId = this.postForm.userId;
      this.customerShow = true;
    },
    onSelectUserCacnle() {
      this.customerShow = false;
      this.userForm.keyword = "";
      this.customerRow = null;
      this.selectUserId = "";
    },
    selUser(e) {
      this.postForm.userId = e;
      this.postForm.userName = this.khList.filter(val => val.userId == e)[0].realName
      console.log(this.postForm, 'eee')

    },
    onSelectUserSave() {
      this.postForm.userId = this.selectUserId;
      this.postForm.userName = this.customerRow.realName;
      this.userForm.keyword = "";
      this.selectUserId = "";
      this.loadKhDetial(this.postForm.userId);
      this.customerShow = false;
      // 选择人重新计算
      this.userCouponId = '';
      this.giftProduct = [];
      this.orderModifyCalc();
    },
    onSelectUserSearch() {
      this.userForm.pageIndex = 1;
      this.loadKhList();
    },
    loadKhList() {
      const $this = this;
      $this.utableLoading = true;
      $this.userForm['filterType'] = 'shopUser';
      UserApi.getUserList($this.userForm, true)
        .then((result) => {
          $this.utableLoading = false;
          const { code, data } = result;
          if (code === 1) {
            $this.khTotal = data.total;
            $this.khList = data.records.map((d) => {
              return {
                realName: d.realName,
                nickName: d.nickName,
                mobile: d.mobile,
                userId: d.userId,
              };
            });
          }
          console.log("客户信息".result);
        })
        .catch((error) => {
          $this.utableLoading = false;
        });
    },
    loadKhDetial(id) {
      const $this = this;
      UserApi.getUserDetail(id)
        .then((result) => {
          const { code, data } = result;
          if (code === 1) {
            $this.userAddressList = data.userAddressList;
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },
    loadZtAdress() {
      const $this = this;
      StoreApi.shoplist({
        pageIndex: 1,
        pageSize: 10000,
      })
        .then((result) => {
          const { code, data } = result;
          if (code === 1) {
            $this.ztAddress = data.records;
          }
        })
        .catch((error) => {
          console.error("自提地址", error);
        });
    },
    khCurrentChange(index) {
      this.userForm.pageIndex = index;
      this.loadKhList();
    },
    orderAsync({ orderId }) {
      const $this = this;
      OrderApi.orderAsync(orderId, true)
        .then((result) => {
          const { code, data, msg } = result;
          if (code === 1) {
            ElMessage.success(msg);

            $this.getData();
          } else {
            ElMessage.error(msg);
          }
        })
        .catch((error) => {
          ElMessage.error("订单数据同步异常");
        });
    },
    fhClick(row) {
      const $this = this;
      if (row.deliveryType === 20) {
        this.fhTitle = "自提发货";
      } else {
        this.fhTitle = "快递发货";
      }
      OrderApi.toDelivery(row.orderId, true).then((result) => {
        const { code, data } = result;
        if (code === 1) {
          // 设置订单
          $this.sendOrder.orderId = data.order.orderId;
          $this.wlOptions = data.expressList;
          $this.fhModel.fhProducts = [];
          if (data.orderProduct && data.orderProduct.length > 0) {
            data.orderProduct.forEach((item) => {
              const json = {
                productName: item.productName,
                productAttr: item.productAttr,
                num: 0,
                productId: item.orderProductId,
                sysl: Number(item.totalNum) - Number(item.deliveryNum),
              };
              $this.fhModel.fhProducts.push(json);
            });
          }
          this.fhShow = true;
        }
      });
    },
    fhShowClick(val) {
      const $this = this;
      const products = this.fhModel.fhProducts;
      this.sendOrder.productList = [];
      if (val) {
        //验证类型
        if ($this.fhTitle !== "自提发货") {
          if (!this.sendOrder.expressId) {
            ElMessage.error("请选择快递公司");
            return;
          }
          if (!this.sendOrder.expressNo) {
            ElMessage.error("请输入快递单号");
            return;
          }
        }
        // 全部发货
        this.sendOrder.allDelivery = this.fhModel.fhlx === 1;
        if (this.fhModel.fhlx === 2) {
          // 部分发货，验证商品
          if (products.length <= 0) {
            ElMessage.error("请选择您要发货的商品");
            return;
          }
          //处理商品
          this.sendOrder.productList = [];
          products.forEach((p) => {
            const json = {
              orderProductId: p.productId,
              deliveryCount: p.num,
            };
            $this.sendOrder.productList.push(json);
          });
        }
        $this.btnloading = true;
        OrderApi.sendToDelivery(this.sendOrder, true)
          .then((result) => {
            const { code, msg } = result;
            if (code === 1) {
              ElMessage.success(msg);
              $this.fhShow = false;
              $this.getData();
            } else {
              ElMessage.error(msg);
            }
            $this.btnloading = false;
          })
          .catch((error) => {
            $this.btnloading = false;
          });
      } else {
        this.fhShow = false;
      }
      console.log("form", this.sendOrder);
      //
    },
    hanlderView(no) {
      this.$router.push({
        path: "/order/order/Detail",
      });
    },
    handleCurrentChange(val) {
      this.searchForm.pageIndex = val;
      this.getData();
    },
    /*每页多少条*/
    handleSizeChange(val) {
      this.curPage = 1;
      this.searchForm.pageSize = val;
      this.getData();
    },

    /*切换菜单*/
    handleClick(tab) {
      let self = this;
      this.searchForm.pageIndex = 1;
      const item = this.tabOptions.find((f) => f.name === tab);
      if (item) {
        this.fileterValue = item.filter;
      } else {
        this.fileterValue = "all";
      }
      self.getData();
    },
    /*获取列表*/
    getData() {
      let self = this;
      const search = this.searchForm;
      search.dataType = self.fileterValue;
      if (search.searchTime && search.searchTime.length > 1) {
        search.startDate = search.searchTime[0];
        search.endDate = search.searchTime[1];
      } else {
        search.startDate = "";
        search.endDate = "";
      }
      self.loading = true;
      OrderApi.orderlist(search, true)
        .then((res) => {
          let list = [];
          for (let i = 0; i < res.data.orderList.records.length; i++) {
            let item = res.data.orderList.records[i];
            list.push(item);
          }
          self.tableData = list;
          console.log("订单列表", list);
          self.totalDataNumber = res.data.orderList.total;
          self.exStyle = res.data.deliveryList;
          self.order_count = res.data.orderCount;
          self.loading = false;
        })
        .catch((error) => {
          self.loading = false;
        });
    },
    /*打开添加*/
    viewClick(row, type) {
      let self = this;
      let params = row.orderId;
      self.$router.push({
        path: "/order/order/Detail",
        query: {
          id: params,
          tk: type,
        },
      });
    },
    /*搜索查询*/
    onSubmit() {
      this.curPage = 1;
      this.tableData = [];
      this.getData();
    },
    onExport: function () {
      const type = this.fileterValue;
      const obj = {
        ...this.searchForm,
        type
      }
      console.log(obj, 'obj')
      OrderApi.exportOrder(obj).then((res) => {
        const blob = new Blob([res], { type: "application/vnd.ms-excel" });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        const fdate = new Date();
        const perx = `${fdate.getFullYear()}-${fdate.getMonth() + 1}-${fdate.getDate()}`;
        a.download = perx + "订单列表.xlsx";
        a.click();
        setTimeout(() => {
          a.remove();
        }, 1000);
      });
    },
    exportCkClick(row) {
      // exportRefund
      OrderApi.deliveryExport({ orderNo: row.orderNo }).then((res) => {
        const blob = new Blob([res], { type: "application/vnd.ms-excel" });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        const fdate = new Date();
        const perx = `${fdate.getFullYear()}-${fdate.getMonth() + 1}-${fdate.getDate()}`;
        a.download = perx + "出库单.xlsx";
        a.click();
        setTimeout(() => {
          a.remove();
        }, 1000);
      });
    },
    handlerRemove(index) {
      const newTable = this.fhModel.fhProducts.filter(
        (fitem, ifndex) => ifndex !== index
      );
      this.fhModel.fhProducts = newTable;
    },
    orderCancle() {
      this.confirmModel.orderId = "";
      this.confirmModel.pickupTime = "";
      this.confirmModel.orderNumber = "";
      this.confirmModel.tradeNo = "";
      this.confirmModel.paySource = "";
      this.confirmModel.payTime = "";
      this.confirmModel.payType = 0;

      this.confirmShow = false;
    },
    orderSave() {

      const $this = this;
      //验证提货时间
      let isValidate = true;
      const products = this.confirmModel.showProducts
      const newProducts = []
      for (let i = 0; i < products.length; i++) {
        const row = products[i]
        if (!row.pickupTime) {
          ElMessage.error("请选择提货时间");
          isValidate = false
          break;
        }

        newProducts.push({
          orderProductId: row.orderProductId,
          pickupTime: row.pickupTime
        })
      }

      if (isValidate) {
        $this.btnloading = true;
        $this.confirmModel.products = newProducts
        OrderApi.confirmOrder($this.confirmModel, true)
          .then((result) => {
            const { code, msg } = result;
            if (code === 1) {
              ElMessage.success(msg);
              $this.orderCancle();
              $this.getData();
            } else {
              ElMessage.error(msg);
            }
            $this.btnloading = false;
          })
          .catch((error) => {
            $this.btnloading = false;
          });
      }
    },
    orderClick(row, type) {
      const $this = this;
      if (type === "确认订单") {
        $this.confirmModel.orderId = row.orderId;
        $this.confirmModel.orderNumber = row.orderNo;
        $this.confirmModel.payType = row.payType;
        //$this.confirmModel
        $this.loadOrderDetail();
        this.pickupTime = null;
        $this.confirmShow = true;
        // payType = 40
      } else if (type === "确认尾款") {
        $this.backForm.orderId = row.orderId;
        $this.backForm.orderNumber = row.orderNo;
        $this.backShow = true;

        // ElMessageBox.confirm('请仔细核查尾款,提交后不可修改', '确认客户已在线下支付尾款?',
        //   {
        //     confirmButtonText: '确定',
        //     cancelButtonText: '取消',
        //     type: 'warning',
        //   }).then(result => {
        //     alert('确定')
        //   }).catch(error => {
        //     alert('取消')
        //   })
      }
      console.log("row", row, type);
    },
    async loadOrderDetail(row) {
      const $this = this;
      const id = $this.confirmModel.orderId;
      this.showProductsLoading = true;
      const { code, data } = await OrderApi.getOrderDetail(id, true);
      if (code === 1) {
        this.showProductsLoading = false
        $this.confirmModel.showProducts = data.productList;
      } else {
        this.showProductsLoading = false
      }
    },
    wkCancle() {
      this.backForm.orderId = "";
      this.backForm.orderNumber = "";
      this.backForm.paySource = "";
      this.backForm.payTime = "";
      this.backForm.tradeNo = "";
      this.backShow = false;
    },
    wkOrderSave() {
      const $this = this;
      this.$refs["backForm"].validate((valid) => {
        if (valid) {
          $this.wkLoad = true;
          OrderApi.confirmBack($this.backForm, true)
            .then((result) => {
              const { code, msg } = result;
              if (code === 1) {
                ElMessage.success(msg);
                $this.wkCancle();
                $this.getData();
              } else {
                ElMessage.error(msg);
              }
              $this.wkLoad = false;
            })
            .catch((error) => {
              $this.wkLoad = false;
            });
        }
      });
    },
    productSearch() {
      this.orderProductForm.pageIndex = 1;
      this.loadProducts();
    },
    prodcutCurrent(index) {
      this.orderProductForm.pageIndex = index;
      this.loadProducts();
    },
    //加载商品
    loadProducts() {
      const $this = this;
      $this.orderProductLoading = true;
      // 不需要基地去查
      // $this.orderProductForm['produceAddress'] = this.postForm.produceAddress

      OrderApi.getSkuProducts($this.orderProductForm, true)
        .then((result) => {
          const { code, data } = result;
          if (code === 1) {
            $this.orderProducts = data.records;
            $this.spTotal = data.total;
          }
          $this.orderProductLoading = false;
        })
        .catch((error) => {
          $this.orderProductLoading = false;
        });
    },
    //选择商品
    orderPSClick(row) {
      // if (row.stockNum == 0) {
      //   return ElMessage.error("该商品库存为0,请重新选择");
      // }
      const $this = this;
      if ($this.orderSelctProduct.length > 0) {
        // const adress = $this.orderSelctProduct.find(
        //   (f) => f.produceAddress !== row.produceAddress
        // );
        // if (adress) {
        //   ElMessage.error("请选择相同基地的商品");
        //   return;
        // }

        const model = $this.orderSelctProduct.find(
          (f) => f.productSkuId === row.productSkuId
        );
        if (!model) {
          $this.orderSelctProduct.push({
            productSkuId: row.productSkuId,
            productName: row.productName,
            productId: row.productId,
            minBuyCount: row.minBuyCount,
            categoryName: row.categoryName,
            categoryParentName: row.categoryParentName,
            sl: row.minBuyCount, //默认最小起订数量
            color: row.color,
            sku: row.sku,
            productPrice: row.productPrice,
            tenThousandPrice: row.tenThousandPrice,
            lakhPrice: row.lakhPrice,
            imagePath: row.imagePath,
            stockNum: parseInt(row.stockNum),
            depositRatio: Number(row.depositRatio),
            productAttr: row.productAttr,
            orderProductType: 10,//创建订单默认为销售
            produceAddress: row.produceAddress,
            produceAddressTxt: row.produceAddressTxt,
          });
        } else {
          ElMessage.error("此商品重复");
        }
      } else {
        $this.orderSelctProduct.push({
          productSkuId: row.productSkuId,
          productName: row.productName,
          categoryName: row.categoryName,
          categoryParentName: row.categoryParentName,
          sl: row.minBuyCount, //默认最小起订数量
          productId: row.productId,
          minBuyCount: row.minBuyCount,
          depositRatio: Number(row.depositRatio),
          color: row.color,
          productPrice: row.productPrice,
          tenThousandPrice: row.tenThousandPrice,
          lakhPrice: row.lakhPrice,
          sku: row.sku,
          imagePath: row.imagePath,
          stockNum: parseInt(row.stockNum),
          productAttr: row.productAttr,
          orderProductType: 10,//创建订单默认为销售
          produceAddress: row.produceAddress,
          produceAddressTxt: row.produceAddressTxt,
        });
      }
      this.selCoupon()
      console.log("选择", row);
    },
    //已选商品删除
    orderPDelete(index) {
      this.orderSelctProduct.splice(index, 1);
      setTimeout(() => {
        this.userCouponId = '';
        this.giftProduct = [];
        this.orderModifyCalc();
      })
    },
  }
};
</script>
<style scoped>
/deep/.el-dropdown {
  font-size: 12px;
  vertical-align: inherit;
  margin-left: 8px;
  color: #67c23a;
  cursor: pointer;
}

::v-deep(.el-scrollbar__bar.is-horizontal) {
  height: 20px;          /* 想多粗就写多大 */
}
</style>
<style lang="scss">
.product-info {
  padding: 10px 0;
  border-top: 1px solid #eeeeee;
}

.calc-data-css {
  span {
    font-weight: bold;
    color: #333;
  }
}

.table-column-btns {
  div {
    display: flex;
    flex-direction: column;

  }
}

.order-code .state-text {
  padding: 2px 4px;
  border-radius: 4px;
  background: #808080;
  color: #ffffff;
  margin-right: 6px;
}

.order-code .state-text-red {
  background: red;
}

.table-wrap .product-info:first-of-type {
  border-top: none;
}

.table-wrap .el-table__body tbody .el-table__row:nth-child(odd) {
  background: #f5f7fa;
}

.pageselect {
  padding: 10px 0px;
  text-align: right;
  float: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}


</style>
